package net.wicp.tams.common.constant;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.lang3.ArrayUtils;

import net.wicp.tams.common.exception.ExceptAll;
import net.wicp.tams.common.exception.ProjectException;

/**
 * 
 * @author 偏锋书生
 *
 */
public enum DateFormatCase {

	YYYY_MM_DD("yyyy-MM-dd", StrPattern.date),

	YYYY_MM_DD_hhmmss("yyyy-MM-dd HH:mm:ss", StrPattern.date_time),

	YYYY_MM_DD_hhmmssSSS("yyyy-MM-dd HH:mm:ss.SSS", StrPattern.date_time_SSS),

	YYYYMMDD("yyyyMMdd", StrPattern.date2),

	yyyyMMddHHmmss("yyyyMMddHHmmss", StrPattern.date_time2),

	yyyyMMddHHmmssSSSS("yyyyMMddHHmmssSSSS", StrPattern.date_time_SSS2),

	TyyyyMMddHHmmss("yyyy-MM-dd'T'HH:mm:ssz", StrPattern.date_time_t3),

	TZyyyyMMddHHmmss("yyyy-MM-dd'T'HH:mm:ss'Z'", StrPattern.date_time_t2),

	TyyyyMMddHHmmssNoZ("yyyy-MM-dd'T'HH:mm:ss", StrPattern.date_time_t1);

	private final String pattern;
	private final StrPattern valuePattern;

	// 这是epoch，unix时间戳零点是utc 1970年1月1日0点整，北京是gmt 8所以变成八点。
	// 简单来说就是数据库出BuG，储存的时间是零，相当于1970年1月1日八点
	private static String[] excludes = new String[] { "0001-01-01 00:00:00", "00010101000000", "1970-01-01 00:00:00",
			"19700101000000", "1970-01-01 08:00:00", "19700101080000" };

	public StrPattern getValuePattern() {
		return valuePattern;
	}

	private DateFormatCase(String pattern, StrPattern valuePattern) {
		this.pattern = pattern;
		this.valuePattern = valuePattern;
	}

	public SimpleDateFormat getInstanc() {
		SimpleDateFormat instanc = new SimpleDateFormat(pattern);
		return instanc;
	}

	public boolean validDateStr(String datestr) {
		if (this.valuePattern == null) {
			return false;
		}
		return this.valuePattern.checkStrFormat(datestr);
	}

	public static DateFormatCase validDateFormat(String datestr) {
		for (DateFormatCase dateFormatCase : DateFormatCase.values()) {
			if (dateFormatCase.validDateStr(datestr)) {
				return dateFormatCase;
			}
		}
		return null;
	}

	public static Date toDate(String datestr) throws ProjectException {
		if (ArrayUtils.contains(excludes, datestr)) {
			throw new ProjectException(ExceptAll.project_datenofitformate, "时间为0，请检查程序是否有问题");
		}
		DateFormatCase validDateFormat = validDateFormat(datestr);
		if (validDateFormat == null) {
			throw new ProjectException(ExceptAll.project_nosupport, "不支持的数据类型");
		} else {
			Date retobj;
			try {
				retobj = validDateFormat.getInstanc().parse(datestr);
				return retobj;
			} catch (ParseException e) {
				throw new ProjectException(ExceptAll.project_formatnofit, e);
			}
		}
	}

}
